package com.cff.shorturl.service.imp;

import java.util.Date;
import java.util.Map;
import com.alibaba.fastjson.JSONObject;
import com.cff.shorturl.context.Context;
import com.cff.shorturl.db.DbFactory;
import com.cff.shorturl.db.DbManager;
import com.cff.shorturl.http.body.HttpRequestMsg;
import com.cff.shorturl.http.body.HttpResponseMsg;
import com.cff.shorturl.http.body.ResCode;
import com.cff.shorturl.http.body.ResType;
import com.cff.shorturl.manager.SequenceManager;
import com.cff.shorturl.service.Service;
import com.cff.shorturl.task.LogTask;
import com.cff.shorturl.task.TreadManager;
import com.cff.shorturl.util.Base62Util;
import com.cff.shorturl.util.StringUtil;

public class GenService implements Service {
	@Override
	public HttpResponseMsg handler(HttpRequestMsg httpRequestMsg) {
		try {
			Map<String, Object> params = httpRequestMsg.getParams();
			String url = (String) params.get("url");
			DbManager db = DbFactory.createDbManager();
			String sql = "select surl from t_short_url where url = ?";
			String surl = db.queryString(sql, new Object[]{url});
			
			LogTask task = new LogTask();
			
			if(StringUtil.isEmpty(surl)){
				int id = SequenceManager.getInstance().offerUrlIdSeq();
				surl = Base62Util.encode(id);
				
				// 加上月份id
				surl = Context.getTimeDiffBase62() + surl;
	
				System.out.println(surl);
				String insql = "insert into t_short_url(surl,url) values (?,?)";
				db.execute(insql, surl, url);
				task.setSurl(surl);
				task.setDate(new Date());
			}else{
				task.setSurl(surl);
				task.setDate(new Date());
				task.setUpdate(true);
			}
			TreadManager.submit(task);
			HttpResponseMsg hrm = httpRequestMsg.getReponse();
			JSONObject json = new JSONObject();
			json.put("shortUrl", surl);
			json.put("originUrl", url);
			hrm.setMessage(json.toJSONString());
			int resCode = ResCode.OK.getValue();
			hrm.setResCode(resCode);
			hrm.setResType(ResType.JSON.getValue());
			return hrm;
		} catch (Exception e) {
			return null;
		}
	}
	
}
